import asyncio
import signal
from app.agent.chat import Chat
from app.config import config
from app.agent.manus import Manus
from app.logger import logger
from halo import Halo

async def main():
    logger.info(f"Environment mode: {config.env.mode}")

    #agent = await Manus.create()
    agent = await Chat.create()
    #agent = Manus()
    # 创建一个事件用于控制程序退出
    stop_event = asyncio.Event()
    
    def handle_exit(signum, frame):
        """处理退出信号"""
        logger.info("Received exit signal. Cleaning up...")
        stop_event.set()
    
    # 注册信号处理器
    signal.signal(signal.SIGINT, handle_exit)
    signal.signal(signal.SIGTERM, handle_exit)

    try:
        while not stop_event.is_set():
            try:
                prompt = input("\n💬Enter a prompt (Ctrl+C to exit): ")
                if not prompt.strip():
                    logger.warning("Empty prompt. Exiting...")
                    break
                
                logger.warning(f"💬Running agent with prompt: {prompt}")
                #清除步骤
                agent.current_step = 0
                with Halo(text='Agent is thinking...', spinner='dots') as spinner:
                    result = await agent.run(prompt)
                logger.warning(f"💬Agent result: \n{result}")
            except asyncio.CancelledError:
                logger.info("Task cancelled. Cleaning up...")
                break
            except KeyboardInterrupt:
                logger.info("Keyboard interrupt received. Cleaning up...")
                break
            except Exception as e:
                logger.error(f"Error: {e}")
                continue
    finally:
        logger.info("Cleaning up resources...")
        await agent.cleanup()
        logger.info("Cleanup completed. Goodbye!")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("Program terminated by user.")
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
    finally:
        logger.info("Program exited.")
